new Vue({
  el: "#app",
  mixins: [Save],
  data() {
    return {
      dataForm: {
        Rules_SerialNumber: "",
        Tracecode_Main_SerialNumber: "",
        CodeQty: "",
      },
      tracecode_detail: [],
      tracecode_rules: [],
      tracecode_rules_detail: [],
      tracecodelog: [],
      loading: false,
      generatedCodes: [
        {
           Code: "",
        },
      ],
      rules: [],
      originalRules: [], // 新增：规则的原始值（用于对比）
    };
  },
  mounted() {
    this.getList();
  },
  methods: {
    
    //获取码规则和码表
    async getList() {
      try {
        const data = await httpRequest({
          url: "/generalBusiness/generalQueryByTableName",
          data: {
            Data: "tracecode_rules",
            Condition: `Row_Status='0'`,
          },
          type: "GET",
        });
        this.tracecode_rules = data;
      } catch (error) {
        this.$message.error("系统错误，请联系开发者!");
        console.error("获取数据失败:", error);
      }
    },

    //生成随机字符
    generateAntiFakeString(length) {
      const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
      let result = "";
      for (let i = 0; i < length; i++) {
        result += chars.charAt(Math.floor(Math.random() * chars.length));
      }
      return result;
    },
    //生成表头
    generateCodeHead(rules) {
      let codeHead = "";
      rules.forEach((rule) => {
        if (rule.Row_Status !== "1") {
          switch (rule.Code_Type) {
            case "时间日期":
              codeHead += parseTime(new Date(), "{y}{m}{d}");
              break;
            case "防伪字符":
              const antiFakeLength = parseInt(rule.Code_Value) || 4;
              codeHead += this.generateAntiFakeString(antiFakeLength);
              break;
            case "自定义字符串":
              codeHead += rule.Code_Value || "";
              break;
            default:
              console.warn("未知的码段类型:", rule.Code_Type);
          }
        }
      });

      return codeHead;
    },
    //生成码
    async setCode() {
      const { Rules_SerialNumber, CodeQty, Tracecode_Main_SerialNumber } =
        this.dataForm;

      if (!Rules_SerialNumber) {
        this.$message.error("请选择规则序列号");
        return false;
      }

      if (!CodeQty || CodeQty <= 0) {
        this.$message.error("请输入有效的生成数量");
        return false;
      }

      try {
        // 获取规则详情
        const [rulesData, detailData] = await Promise.all([
          httpRequest({
            url: "/generalBusiness/generalQueryByTableNameWithOriginal",
            data: {
              Data: "tracecode_rules",
              Condition: `Rules_SerialNumber='${Rules_SerialNumber}' AND Row_Status='0'`,
            },
          }),
          httpRequest({
            //generalQueryByTableNameWithOriginal
            url: "/generalBusiness/generalQueryByTableName",
            data: {
              Data: "tracecode_rules_detail",
              Condition: `Rules_SerialNumber='${Rules_SerialNumber}' AND Row_Status='0'`,
            },
            type: "GET",
          }),
        ]);


        if (!rulesData || rulesData.length === 0) {
          this.$message.error("未找到对应的规则配置");
          return false;
        }
  
        let rule = rulesData;
        let crule = rulesData[0];
        const codeHead = this.generateCodeHead(detailData);
        const startSerial = parseInt(crule.Code_Serial) || 0;
        const serialLength = crule.Code_Seriallength || 6;
        const endSerial = startSerial + parseInt(CodeQty);
        let CodeSerial = endSerial.toString().padStart(serialLength, "0");
        // 生成码列表
        this.generatedCodes = [];
        for (let i = startSerial + 1; i <= endSerial; i++) {
          const serialPart = i.toString().padStart(serialLength, "0");
          const fullCode = codeHead + serialPart;
          this.generatedCodes.push(fullCode);
        }
        this.tracecode_detail = this.generatedCodes.map((code, index) => {
          return {
            Tracecode_Main_SerialNumber: Tracecode_Main_SerialNumber,
            Code: code,
          };
        });
        this.tracecodelog = this.generatedCodes.map((code, index) => {
          return {
            Code: code,
          };
        });
        // 更新 tracecode_rules - 只更新与当前选择的 Rules_SerialNumber 匹配的记录
        rule[0].Code_Serial = CodeSerial;
        this.rules = rule;
        this.originalRules = JSON.parse(JSON.stringify(this.tracecode_rules));
        // 不匹配的记录原样返回

   
        this.dataForm.Result = "共生成" + CodeQty + "条码";
   

        return true;
      } catch (error) {
        console.error("生成码失败:", error);
        this.$message.error("生成码失败，请联系开发者!");
        return false;
      }
    },

    async handleSubmit() {
      // 表单验证
      const allValid = await this.validateAllForms();
      if (!allValid) {
        this.$message.warning("存在未填写的必填项！");
        return;
      }

      // 生成码
      const codeGenerated = await this.setCode();
      if (!codeGenerated) {
        return;
      }

      this.loading = true;

      try {
        const lJSONObject_DataSet = this.generateStructure();

        let ppp = "Modify";

        lJSONObject_DataSet[ppp];
        lJSONObject_DataSet.Modify = { tracecode_rules: [...this.rules] };


        // 后续请求逻辑保持不变...
        const res = await httpRequest({
          contentType: "JSON",
          url: "/generalBusiness/generalSaveByRequestBody",
          data: JSON.stringify({
            Data: lJSONObject_DataSet,
          }),
        });

        if (res.Status === "success") {
          this.$message.success("提交成功");
          setTimeout(() => {
            window.location.href = "./index.html";
          }, 1000);
        } else {
          this.$message.error("提交失败，请重试！");
        }
      } catch (error) {
        console.error("提交失败:", error);
        this.$message.error("系统错误，请联系开发者!");
      } finally {
        this.loading = false;
      }
    },

    // 预览生成的码
    previewCodes() {
      if (this.generatedCodes.length > 0) {
        const previewText = this.generatedCodes.slice(0, 5).join("\n");
        if (this.generatedCodes.length > 5) {
          this.$message.info(
            `前5个码:\n${previewText}\n...共${this.generatedCodes.length}个码`
          );
        } else {
          this.$message.info(`生成的码:\n${previewText}`);
        }
      }
    },

    // 重置表单
    resetForm() {
      this.dataForm = {
        Rules_SerialNumber: "",
        Tracecode_Main_SerialNumber: "",
        CodeQty: 1,
      };
      this.generatedCodes = [];
      this.tracecode_detail = [];
    },
  },
});
